#!/usr/bin/python3
# -*- coding: utf-8 -*-


from flask import Flask,request,make_response,send_from_directory,abort,render_template,jsonify
from datetime import datetime,timedelta
import requests,requests_cache
from flask_cors import CORS
from .config import *


app = Flask(__name__)
CORS(app)

requests_cache.install_cache('BTMExplorer', backend='sqlite', expire_after=30)


@app.route('/',methods=['GET'])
def index():
    pass


@app.route('/api/price',methods=['GET'])
def price():
    '''
    BTM 当前价格以及历史价格数据
    '''
    headers = {'Content-Type':'application/x-www-form-urlencoded'}
    # TODO
    # Spiders
    data = {'now': 0.2, 'history': []}
    return jsonify(data)

@app.route('/api/hash',methods=['GET'])
def hashrate():
    '''
    最近三个月的Bytom哈希增长曲线
    '''
    headers = {
        'User-Agent': User_Agent
    }
    now = 0
    before = 0
    data = requests.get('https://blockmeta.com/api/v2/stat/difficulty?from=1530874300&to=15312384200',headers=headers).json()
    return jsonify(data)


@app.route('/api/miner',methods=['GET'])
def miner():
    '''
    BTM各大矿池算力分布
    '''
    headers = {
        'User-Agent':User_Agent
    }
    data = requests.get('https://blockmeta.com/api/v2/stat/miner',headers=headers).json()
    return jsonify(data)

@app.route('/api/blocks',methods=['GET'])
def blocks():
    '''
    返回最新挖出的二十个块
    '''
    data = requests.get('https://blockmeta.com/api/v2/blocks?page=1&limit=20').json()
    return jsonify(data)

@app.route('/api/search/<one_or_many>',methods=['POST'])
def search(one_or_many):
    '''
    1.先判断单次查询还是批量查询
    2.再根据内容判断是地址还是交易id
    '''
    headers = {
        'User-Agent': User_Agent
    }
    if one_or_many == 'one':
        addrOrTx = request.json.get('content')
        if addrOrTx:
            if 'bm' in addrOrTx[:3]:
                data = requests.get('https://blockmeta.com/api/v2/address/'+addrOrTx,headers=headers).json()
                return jsonify(data)
            else:
                data = requests.get('https://blockmeta.com/api/v2/transaction/').json()
                return jsonify(data)
        else:
            abort(401)
    if one_or_many == 'many':
        pass
    else:
        abort(401)


if __name__ == '__main__':
    app.run(debug=True)




